# /usr/bin/python
# -*- coding: utf-8 -*-

import os,sys
BASE_DIR = os.path.dirname(os.path.abspath(os.curdir))
sys.path.append(BASE_DIR)
from models.MySQL import MySQL
from conf.setting import templates 
from util.log import get_stream_logger
from models.Zabbix import ZBX

logger = get_stream_logger("add_grp_tpl")

Z = ZBX()
hosts = Z.get_host(host="")
with MySQL() as cur:
    for host in hosts:
        inter = Z.get_interface(hostids=host["hostid"])
        for i in inter:
            if i["main"] == '1':
                ip = i["ip"]

        cmd = "SELECT id FROM host WHERE ip='%s'"%ip
        res = cur.search(cmd)

        if len(res) == 0:
            logger.error("Cannot find host %s"%ip)
            continue
        
        hostid = res[0][0]

        group_cmd = "SELECT grp_id FROM grp_host WHERE host_id='{hostid}'".format(hostid=hostid)
        group_res = cur.search(group_cmd)
        if len(group_res) == 0:
             logger.error("Host %s does not belong any group"%ip)
             continue
        
        for g in group_res:
            group_id = g[0]

            for t in host["parentTemplates"]:
                tpl_name = t["name"]
                tpl_cmd = "SELECT id  from tpl WHERE tpl_name='%s'"%tpl_name
                tpl_res = cur.search(tpl_cmd)
                if len(tpl_res) == 0:
                    logger.error("Cannot find template %s"%tpl_name)
                    continue
                tpl_id =tpl_res[0][0]

                check_cmd = "SELECT * FROM grp_tpl WHERE grp_id='{grp_id}' AND tpl_id='{tpl_id}'".format(grp_id=group_id,tpl_id=tpl_id)
                check_res = cur.cur.execute(check_cmd)
                if check_res == 0:
                    insert_cmd = "INSERT INTO grp_tpl VALUES ('{grp_id}','{tpl_id}','root')".format(grp_id=group_id,tpl_id=tpl_id)
                    insert_res = cur.update(insert_cmd)
                    if insert_res != 1:
                        logger.error("Insert info grp_tpl failed, group:{grp_id},template:{tpl_id}".format(grp_id=group_id,tpl_id=tpl_id))
    